# coding:utf-8
import json
from . import constants
from flask_restful import Resource
from comment.models.user import User
from comment.models.example.SendMessage1 import send_messaga
from flask import current_app, request
import random
from comment.utils.limiter import limiter as lmt
from flask_limiter.util import get_remote_address
from comment.utils.redis import redis_client
from flask_restful.reqparse import RequestParser
from comment.utils import parser
from comment.models import db
from comment.utils.tokens_pyjwt import generate_tokens
from comment.utils.decorators import login_required
from flask import g
class Shopping_User(Resource):
    method_decorators = {
        'get':[login_required]
    }
    def get(self):
        current_app.logger.info('测试')
        return {'hello': '测试'}


class User_SMS(Resource):
    # 发送验证码的短信
    error_message = 'Tom many requests.'
    # 三个参数，参数1：限制的频率，参数2：key_func传的是必须是函数,参数3：如果超出限制后的提示信息
    decorators = [
        # 三个参数：参数1：限流的速率,参数2：key_func,参数3：如果超出限制之后的提示信息
        lmt.limit(constants.LIMIT_SMS_CODE_BY_MOBILE,
                  key_func=lambda: request.args['phone'],
                  error_message=error_message),
        lmt.limit(constants.LIMIT_SMS_CODE_BY_IP,
                  key_func=get_remote_address,
                  error_message=error_message)
    ]

    def get(self):
        phone = request.args.get('phone')
        code = random.randint(1000, 9999)
        result = send_messaga(phone, str(code))
        result = json.loads(result)  # 把json编程字典
        # result 往里面添加手机号码
        result['phone'] = phone
        # result往里添加手机号码
        # 把短信验证码保存到redis数据库中,验证码时效为5分钟
        redis_client.setex('shopping:code:{}'.format(phone), constants.SMS_COOE_EXPIRES,
                           code)  # 参数1 key.参数2，时效性，参数3，验证码
        return result


class AuthorizationCodeResource(Resource):

    # 提交手机号和验证码，开始验证
    def post(self):
        rp = RequestParser()
        rp.add_argument('phone', type=parser.mobile, required=True)
        rp.add_argument('code', type=parser.regex, required=True)
        args = rp.parse_args()
        phone = args.phone
        code = args.code

        # 从redis取出数据，开始验证

        key = 'shopping:code:{}'.format(phone)
        try:
            real_code = redis_client.get(key)  # 从redis返回的是字节数据
        except ConnectionError as e:
            current_app.logger.error(e)
            return {'message': 'redis db connect error'}, 400

        # 开始校验
        if real_code.decode() != code:
            return {'message': 'Invalid code'}, 400

        return {'phone': phone, 'msg': 'code ok'}


class RegisterUserResource(Resource):
    # 填写账号信息，完成用户的注册
    def post(self):
        rp = RequestParser()
        rp.add_argument('phone', type=parser.mobile, required=True)
        rp.add_argument('username', required=True)
        rp.add_argument('password', required=True)
        rp.add_argument('email', type=parser.email, required=True)
        args = rp.parse_args()
        phone = args.phone
        username = args.username
        email = args.email
        password = args.password

        # 判断用户名是否唯一
        u = User.query.filter(User.username == username).first()
        # 用户名重复
        if u:
            current_app.logger.info('{}已存在'.format(username))
            return {'message':'The username already exists.'},400

        u = User(username=username,pwd=password,email=email,phone=phone,status=0)
        db.session.add(u)
        db.session.commit()
        return {'msg':'ok'}


class UserLoginResource(Resource):
    #登录
    def post(self):
        # rp = RequestParser()
        # rp.add_argument('username', required=True)
        # rp.add_argument('password', required=True)
        # args = rp.parse_args()
        # password = args.password
        # username = args.username
        #上面方法也行
        username=request.form.get('username')
        password=request.form.get('password')

        if not all([username,password]):
            return {'message':'数据不完整'}

        u=User.query.filter(User.username==username).first()
        if u:
            if u.check_pwd(password):
                token=generate_tokens(u.id)
                return {'msg':'ok','token':token,'username':username},200
        return {'message':'错误'}


class UserLoginOutResource(Resource):
    def post(self):
        if g.user_id:
            g.user_id=None
        return {'msg':'退出登录'}

class IsExistPhoneResource(Resource):
    #判断手机号是否存在
    def post(self):
        phone=request.form.get('phone')

        user=User.query.filter(User.phone==phone).first()
        if user:#如果用户有，表示手机号存在
            return {'isExist':True,'message': '已注册','code':201}
        return {'msg':'手机号可以注册'}

